<?php
/**
 * 数据库连接测试脚本
 */

// 引入自动加载
require_once __DIR__ . '/vendor/autoload.php';

// 加载配置
$config = require __DIR__ . '/config/database.php';

try {
    // 获取数据库配置
    $dbConfig = $config['connections']['admin'];
    
    echo "正在测试数据库连接...\n";
    echo "主机: {$dbConfig['host']}\n";
    echo "端口: {$dbConfig['port']}\n";
    echo "数据库: {$dbConfig['database']}\n";
    echo "用户名: {$dbConfig['username']}\n";
    echo "字符集: {$dbConfig['charset']}\n";
    echo "表前缀: {$dbConfig['prefix']}\n";
    echo "----------------------------------------\n";
    
    // 创建PDO连接
    $dsn = "mysql:host={$dbConfig['host']};port={$dbConfig['port']};dbname={$dbConfig['database']};charset={$dbConfig['charset']}";
    $pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);
    
    echo "✅ 数据库连接成功！\n";
    
    // 测试查询
    $stmt = $pdo->query("SELECT VERSION() as version");
    $result = $stmt->fetch();
    echo "MySQL版本: {$result['version']}\n";
    
    // 查看数据库中的表
    $stmt = $pdo->query("SHOW TABLES LIKE '{$dbConfig['prefix']}%'");
    $tables = $stmt->fetchAll();
    
    if (empty($tables)) {
        echo "⚠️  数据库中没有找到以 '{$dbConfig['prefix']}' 为前缀的表\n";
        echo "建议运行数据库迁移命令创建表结构\n";
    } else {
        echo "📋 数据库中的表:\n";
        foreach ($tables as $table) {
            $tableName = array_values($table)[0];
            echo "  - {$tableName}\n";
        }
    }
    
    // 测试模型连接
    echo "\n正在测试模型连接...\n";
    
    // 启动应用
    support\App::run();
    
    // 测试AdminModel
    $adminModel = new app\model\AdminModel();
    $count = $adminModel->count();
    echo "✅ 模型连接成功！管理员表记录数: {$count}\n";
    
} catch (PDOException $e) {
    echo "❌ 数据库连接失败: " . $e->getMessage() . "\n";
    echo "请检查以下配置:\n";
    echo "1. MySQL服务是否启动\n";
    echo "2. 数据库配置是否正确\n";
    echo "3. 用户名密码是否正确\n";
    echo "4. 数据库是否存在\n";
} catch (Exception $e) {
    echo "❌ 其他错误: " . $e->getMessage() . "\n";
}

echo "\n测试完成！\n"; 